<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >

      <el-form-item label="客户" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          clearable
          filterable
          placeholder="请选择客户"
          class="!w-120px"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <!--        <el-button-->
        <!--          type="primary"-->
        <!--          plain-->
        <!--          @click="openForm('create')"-->
        <!--          v-hasPermi="['erp:finance-receipt-batch:create']"-->
        <!--        >-->
        <!--          <Icon icon="ep:plus" class="mr-5px" /> 新增-->
        <!--        </el-button>-->
        <!--        <el-button-->
        <!--          type="success"-->
        <!--          plain-->
        <!--          @click="handleExport"-->
        <!--          :loading="exportLoading"-->
        <!--          v-hasPermi="['erp:finance-receipt-batch:export']"-->
        <!--        >-->
        <!--          <Icon icon="ep:download" class="mr-5px" /> 导出-->
        <!--        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" border :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!--      <el-table-column label="订单编号" align="center" prop="id" />-->
      <!--      <el-table-column label="收款编号集合" align="center" prop="receiptIds" />-->

      <el-table-column fixed="left" label="操作" width="60" align="center">

        <template #default="scope">
          <el-popover style="position: relative" :visible="popoverVisible == scope.row.id"
                      placement="bottom-start"
                      :width="60">
            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="primary"
                  @click="handleAddReceipt(scope.row)"
                >
                  添加收款单
                </el-button>
              </el-col>
            </el-row>

            <div class="popoverCloseBtn" @click="closePopover()">关闭</div>
            <template #reference>
              <img src="@/assets/imgs/more_edit.png" class="linkBtn" @click="lookBind(scope.row)"
                   @contextmenu.prevent="handleRightClick(scope.row.id)"
              />
            </template>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="客户" align="center" prop="customerName"/>
      <el-table-column label="合计金额" align="center" prop="amount"/>
      <el-table-column label="已收金额" width="100px" prop="receiptAmount">
        <template #default="scope">
          <el-input class="no-border-input"
                    @change="handleChangeReceiptAmount(scope.row)" type="text"
                    v-model="scope.row.receiptAmount"/>
        </template>
      </el-table-column>
      <el-table-column label="待收金额" align="center" prop="">
        <template #default="scope">
          <span>{{ scope.row.amount - scope.row.receiptAmount }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="备注" align="center" prop="remark" />-->

      <el-table-column label="备注" align="center" prop="remark">
        <template #default="scope">
          <el-input class="no-border-input"
                    @change="handleChangeRemark(scope.row)" type="text" v-model="scope.row.remark"/>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>


  <Dialog title="新增收款列表" v-model="receiptDialogVisible" width="50%">
    <el-table v-loading="loading" ref="multipleTableRef"  @selection-change="handleSelectionChange"
              border :data="receiptList" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="selection" fixed="left" width="40"/>
      <el-table-column label="客户" width="200" prop="customerName"/>
      <el-table-column label="金额" width="120" prop="totalPrice"/>
      <el-table-column label="对账状态" width="120" prop="checkStatus">
        <template #default="scope">
          <el-tag v-if="scope.row.checkStatus == 1" type="danger">未对账</el-tag>
          <el-tag v-else-if="scope.row.checkStatus == 3" type="success">已对账</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
      />
      <el-table-column label="订单编号" width="160" align="center" prop="no"/>
    </el-table>
    <!-- 分页 -->


    <template #footer>
      <Pagination
        :total="receiptTotal"
        v-model:page="receiptQueryParams.pageNo"
        v-model:limit="receiptQueryParams.pageSize"
        @pagination="getReceiptList"
      />
      <el-button @click="submitAddReceipt" type="primary" :disabled="formLoading">新 增</el-button>
      <el-button @click="receiptDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>


  <!-- 表单弹窗：添加/修改 -->
  <FinanceReceiptBatchForm ref="formRef" @success="getList"/>
</template>

<script setup lang="ts">
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {FinanceReceiptBatchApi, FinanceReceiptBatchVO} from '@/api/erp/finance/receiptBatch'
import FinanceReceiptBatchForm from './FinanceReceiptBatchForm.vue'
import {ElLoading, ElMessage} from "element-plus";
import {ReceiptBatchApi} from "@/api/dispatch/receiptbatch";
import {ref} from "vue";
import {CustomerApi, CustomerVO} from "@/api/erp/sale/customer";
import {PaymentApi} from "@/api/dispatch/payment";
import {FinanceReceiptApi} from "@/api/erp/finance/receipt";

/** 销售收款对账单 列表 */
defineOptions({name: 'FinanceReceiptBatch'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化
const customerList = ref<CustomerVO[]>([]) // 客户列表
const loading = ref(true) // 列表的加载中
const list = ref<FinanceReceiptBatchVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  receiptIds: undefined,
  amount: undefined,
  receiptAmount: undefined,
  customerName: undefined,
  remark: undefined,
  status: undefined,
  sort: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const formLoading = ref(false)
const receiptTotal = ref(0) // 列表的总页数
const receiptDialogVisible = ref(false)
const multipleTableRef = ref()
const multipleSelection = ref([])
const receiptList = ref([])
const receiptQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerId: undefined,
  checkStatus: 1
})
/** 查询收款列表 */
const getReceiptList = async () => {
  loading.value = true
  try {
    const data = await FinanceReceiptApi.getFinanceReceiptPage(receiptQueryParams)
    if (data == null){
      receiptList.value = [];
      receiptTotal.value =0;
      return;
    }
    receiptList.value = data.list;
    receiptTotal.value = data.total;
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const batchId = ref(undefined);
const handleAddReceipt = async (row) => {

  batchId.value = row.id;

  receiptDialogVisible.value = true
  receiptQueryParams.customerId = row.customerId;
  await getReceiptList();

  popoverVisible.value = null;
}



const submitAddReceipt = async () => {

  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择收款单');
    return;
  }
  //新增中...
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '新增中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    await FinanceReceiptApi.bindBatch(batchId.value,multipleSelection.value)
    receiptDialogVisible.value = false;
    getList();
  }finally {
    loadingInstance.close();
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await FinanceReceiptBatchApi.getFinanceReceiptBatchPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}


/**
 * 已收金额
 * @param row
 */
const handleChangeReceiptAmount = async (row) => {
  try {

    //金额不能小于0
    if (row.receiptAmount < 0 || row.receiptAmount == null || row.receiptAmount == '') {
      ElMessage.error('已收金额不能小于0');
      return;
    }
    if (row.amount < row.receiptAmount) {
      ElMessage.error('已收金额不能大于总金额');
      return;
    }

    await message.confirm('确定要修改已收金额吗?');

    await FinanceReceiptBatchApi.updateReceiptAmount(row);

    //提示
    ElMessage.success('修改成功');

  } finally {
    getList();
  }

}


/**
 * 修改备注
 * @param row
 */
const handleChangeRemark = async (row) => {
  try {
    await message.confirm('确定要修改备注吗?');
    await FinanceReceiptBatchApi.handleChangeRemark(row);
    //提示
    ElMessage.success('修改成功');
  } finally {
    getList();
  }

}


const popoverVisible = ref(null);
const closePopover = async () => {
  popoverVisible.value = null;
}
const handleRightClick = (id) => {
  popoverVisible.value = id;
};


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}


/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await FinanceReceiptBatchApi.deleteFinanceReceiptBatch(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

const {push} = useRouter()
const lookBind = (row) => {
  push({
    path: "/erp/finance/receipt/receipt",
    query: {doType: "query", data: row.receiptIds}
  });
}


/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await FinanceReceiptBatchApi.exportFinanceReceiptBatch(queryParams)
    download.excel(data, '销售收款对账单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {

  // 加载客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  getList()
})

onActivated(()=>{
  getList();
})
</script>
